// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: "yiliaojiufeng-6gt0kj1l1df8b7b7",
    traceUser: true,
})

// 云函数入口函数



const db = cloud.database()
exports.main = async (event, context) => {
    var a = []
    const wxContext = cloud.getWXContext()
    const $ = db.command.aggregate
    await db.collection('readHistory').aggregate()
        .match({
            _openid: wxContext.OPENID
        })
        .group({
            _id: '$newsId',
            maxTime: $.max('$time')
        })
        .end()
        .then(res => {
            a = res.list
            a.sort(function (x,y) {
                return y.maxTime-x.maxTime;
            });
        })
        .catch(err => console.error(err))
        console.log(a)

    var i = 0
    var myStar = []
    var temp = {}

    for (i = 0; i < a.length; i++) {
        temp = await db.collection('news_article').where({
            _id: a[i]._id
        }).get()
        console.log(temp)
        myStar.push(temp.data[0])
    }

    return myStar 
}